package edu.ccut.saturn.authority.core.dept;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;

public class GetDeptTreeforSelectTag extends DefaultComponent {
	@Override
	@SuppressWarnings("unchecked") 

	public void execute(IParameterContext parameterContext) throws Exception {
		List<SaturnData> deptList = (List) parameterContext.getParameterValue(0);
		List<Map<String, String>> deptMapList = new ArrayList<Map<String, String>>();
		//Map<String, String> map0 = new HashMap<String, String>();
		//String mapValue = new String("\u65E0\u90E8\u95E8"); 
		//map0.put("key", "");  
		//map0.put("value", mapValue); 
		//deptMapList.add(map0);
		if (deptList != null) {
			this.generateDeptTree(deptList, this.getRootDept(deptList),
					deptMapList, ""); 
		}
		parameterContext.setParameter(1, deptMapList);
	}

	private List<SaturnData> getRootDept(List<SaturnData> depts) {
		List<SaturnData> deptRoots = new ArrayList<SaturnData>();

		if (depts != null) {
			for (SaturnData dept : depts) {
				String parentId = dept.getString("parent_id"); 

				if (parentId == null || parentId.equals("")) { 
					deptRoots.add(dept);
				}
			}
		}

		return deptRoots;
	}

	private List<SaturnData> getChildrenDept(List<SaturnData> depts,
			String parentId) {
		if (depts != null) {
			List<SaturnData> deptChildren = new ArrayList<SaturnData>();
			for (SaturnData dept : depts) {
				String parentIdKey = dept.getString("parent_id"); 

				if (parentIdKey != null && parentIdKey.equals(parentId)) {
					deptChildren.add(dept);
				}
			}

			return deptChildren;
		}

		return null;
	}

	private void generateDeptTree(List<SaturnData> allDepts,
			List<SaturnData> deptNodes, List<Map<String, String>> deptMapList,
			String space) {
		if (deptNodes != null && !deptNodes.isEmpty()) {
			for (SaturnData dept : deptNodes) {
				String id = dept.getString("id"); 
				String value = space + dept.getString("name"); 

				Map<String, String> deptMapNode = new HashMap<String, String>();

				deptMapNode.put("key", id); 
				deptMapNode.put("value", value); 
				deptMapList.add(deptMapNode);

				generateDeptTree(allDepts, this.getChildrenDept(allDepts, id),
						deptMapList, space + "+-- "); 
			}
		}
	}
}